package com.rc.saas.tenant.controller.enterprise;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.mq.MqConfig;
import com.rc.saas.tenant.common.mq.MqProducer;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadComponent;
import com.rc.saas.tenant.config.UpYunConfig;
import com.rc.saas.tenant.model.enterprise.EnterpriseMember;
import com.rc.saas.tenant.model.enterprise.EnterpriseMemberApply;
import com.rc.saas.tenant.model.enterprise.EnterpriseMemberExample;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.tenant.TenantRole;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.enterprise.EnterpriseMemberApplySearch;
import com.rc.saas.tenant.search.tenant.TenantRoleSearch;
import com.rc.saas.tenant.service.enterprise.EnterpriseMemberApplyService;
import com.rc.saas.tenant.service.enterprise.EnterpriseMemberService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.enterprise.EnterpriseMemberApplyResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author frog
 * @data 2021/2/04
 */
@Controller
@RequestMapping("/enterpriseMemberApply")
public class EnterpriseMemberApplyController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(EnterpriseMemberApplyController.class);

    @Autowired
    private EnterpriseMemberApplyService enterpriseMemberApplyService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private UpYunConfig upYunConfig;

    @Autowired
    private EnterpriseMemberService enterpriseMemberService;

    @Autowired
    private UploadComponent uploadComponent;

    @Autowired
    private MqProducer mqProducer;


    /**
     * 跳转企业会员审核页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String enterpriseMemberApplyPage() {
        return "/templates/enterprise/enterpriseMemberApply/enterpriseMemberApply";
    }

    /**
     * 返回企业会员审核列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listEnterpriseMemberApply", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageEnterpriseMemberApply(EnterpriseMemberApplySearch search) {
        PageInfo<EnterpriseMemberApplyResult> pageInfo = enterpriseMemberApplyService.listPageEnterpriseMemberApply(search);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出企业列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(EnterpriseMemberApplySearch search, HttpServletResponse response) {
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            ExportUtils.setDefaultPaging(search);
            PageInfo<EnterpriseMemberApplyResult> pageInfo = enterpriseMemberApplyService.listPageEnterpriseMemberApply(search);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("企业列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), EnterpriseMemberApplyResult.class).sheet("企业列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出企业列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }


    /**
     * 跳转审核记录页面
     *
     * @return
     */
    @RequestMapping(value = "/applyRecord/{enterpriseApplyId}", method = RequestMethod.GET)
    public String applyRecord(@PathVariable("enterpriseApplyId") Long enterpriseApplyId, Model model) {
        EnterpriseMemberApply enterpriseMemberApply = enterpriseMemberApplyService.selectByPrimaryKey(enterpriseApplyId);
        model.addAttribute("enterpriseMemberApply", enterpriseMemberApply);
        return "/templates/enterprise/enterpriseMemberApply/editEnterpriseMemberApply";
    }


    /**
     * 保存审核
     *
     * @param enterpriseMemberApply
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saveApplyRecord", method = RequestMethod.POST)
    public TResponse saveApplyRecord(EnterpriseMemberApply enterpriseMemberApply,
                                     @RequestParam(value = "file1", required = false) MultipartFile file1,
                                     @RequestParam(value = "file2", required = false) MultipartFile file2) {
        TenantUser user = ShiroUtils.getSessionUser();
        if (file1 != null && file1.getSize() != 0 && file1.getContentType().contains("image")) {
            String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file1);
            enterpriseMemberApply.setCompanyImg1(imgUrl);
        }
        if (file2 != null && file2.getSize() != 0 && file2.getContentType().contains("image")) {
            String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file2);
            enterpriseMemberApply.setCompanyImg1(imgUrl);
        }


        try {
            TResponse tResponse = enterpriseMemberApplyService.saveApplyRecord(enterpriseMemberApply, user);
            return tResponse;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return TResponse.FAIL(e.getMessage());
        }
    }

    /**
     * 审核
     * @param id
     * @param status
     * @param auditRemark
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateEnterpriseApplyForAudit", method = RequestMethod.POST)
    public TResponse updateEnterpriseApplyForAudit(Long id, String status, String auditRemark) {

        EnterpriseMemberApply enterpriseApply = enterpriseMemberApplyService.selectByPrimaryKey(id);

        EnterpriseMemberExample enterpriseExample = new EnterpriseMemberExample();
        enterpriseExample.createCriteria().andEnterpriseNameEqualTo(enterpriseApply.getEnterpriseName());
        List<EnterpriseMember> list = enterpriseMemberService.selectByExample(enterpriseExample);
        if (!CollectionUtils.isEmpty(list)) {
            return TResponse.FAIL("失败：已存在该企业");
        }

        TResponse tResponse = enterpriseMemberApplyService.updateEnterpriseApplyForAudit(id, status, auditRemark);
        return tResponse;
    }

    /**
     * 保存申请
     */
    @ResponseBody
    @RequestMapping(value = "/saveEnterpriseApply", method = RequestMethod.POST)
    public TResponse saveEnterpriseApply(EnterpriseMemberApply enterpriseMemberApply) {
        enterpriseMemberApplyService.saveEnterpriseApply(enterpriseMemberApply);
        return TResponse.SUCCESS();

    }


    /**
     * 企业详情
     *
     * @return
     */
    @RequestMapping(value = "/detail/{enterpriseApplyId}", method = RequestMethod.GET)
    public String detailEnterpriseApply(@PathVariable("enterpriseApplyId") Long enterpriseApplyId, Model model) {
        EnterpriseMemberApply enterpriseMemberApply = enterpriseMemberApplyService.selectByPrimaryKey(enterpriseApplyId);
        model.addAttribute("enterpriseMemberApply", enterpriseMemberApply);
        return "/templates/enterprise/enterpriseMemberApply/detailEnterpriseApply";
    }

    /**
     * 企业详情
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public TResponse delete(@PathVariable("id") Long id, Model model) {
         enterpriseMemberApplyService.deleteByPrimaryKey(id);
         return TResponse.SUCCESS();
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addEnterpriseApply() {
        return "/templates/enterprise/enterpriseMemberApply/addEnterpriseApply";
    }

    /**
     * 增加企业申请
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addEnterpriseApply", method = RequestMethod.POST)
    public TResponse addEnterpriseApply(EnterpriseMemberApply enterpriseMemberApply,
                                   @RequestParam(value = "file1", required = false) MultipartFile file1,
                                   @RequestParam(value = "file2", required = false) MultipartFile file2) {
        TenantUser user = ShiroUtils.getSessionUser();
        if (file1 != null && file1.getSize() != 0 && file1.getContentType().contains("image")) {
            String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file1);
            enterpriseMemberApply.setCompanyImg1(imgUrl);
        }
        if (file2 != null && file2.getSize() != 0 && file2.getContentType().contains("image")) {
            String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file2);
            enterpriseMemberApply.setCompanyImg1(imgUrl);
        }
        enterpriseMemberApplyService.insertReturnId(enterpriseMemberApply);

        Map<String, Long> map = new HashMap<>();
        map.put("enterpriseApplyId", enterpriseMemberApply.getEnterpriseApplyId());
        mqProducer.send(MqConfig.platform_apply, JSON.toJSONString(map), 1);
        return TResponse.SUCCESS();
    }

}
